<?php

namespace app\api\controller\user\dealer;

use app\api\controller\Controller;
use app\api\model\dealer\Setting;
use app\api\model\dealer\User as DealerUserModel;
use app\api\model\dealer\Order as OrderModel;
use think\Db;
/**
 * 分销商订单
 * Class Order
 * @package app\api\controller\user\dealer
 */
class Order extends Controller
{
    /* @var \app\api\model\User $user */
    private $user;

    private $dealer;
    private $setting;

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {
        parent::_initialize();
        // 用户信息
        $this->user = $this->getUser();
        // 分销商用户信息
        $this->dealer = DealerUserModel::detail($this->user['user_id']);
        // 分销商设置
        $this->setting = Setting::getAll();
    }

    /**
     * 分销商订单列表
     * @param int $settled
     * @return array
     * @throws \think\exception\DbException
     */
    // public function lists($settled = -1)
    // {
    //     $model = new OrderModel;
    //     $list = $model->getList($this->user['user_id'], (int)$settled);
    //     dump($list->toArray());die;
    //     return $this->renderSuccess([
    //         // 提现明细列表
    //         'list' => $list,
    //         // 页面文字
    //         'words' => $this->setting['words']['values'],
    //     ]);
    // }
    public function lists($settled = -1)
    {
        // url ?order_type=1/2；不传则不过滤
        $orderType = (int)input('order_type', 1);

        $model = new OrderModel;
        $list  = $model->getList($this->user['user_id'], (int)$settled);

        // 不筛选时，直接返回原分页对象，前端完全无感
        if ($orderType <= 0) {
            return $this->renderSuccess([
                'list'  => $list,
                'words' => $this->setting['words']['values'],
            ]);
        }

        // 需要按 order_type 过滤：把分页转数组做二次处理
        $arr = $list->toArray();

        if (!empty($arr['data'])) {
            // 收集当前页所有 order_id
            $orderIds = array_values(array_unique(array_column($arr['data'], 'order_id')));

            // 一次性查出 order_id => order_type 的映射（Db::name('order') 会走前缀到 yoshop_order）
            $typeByOrderId = [];
            if (!empty($orderIds)) {
                $typeByOrderId = Db::name('order')
                    ->whereIn('order_id', $orderIds)
                    ->column('order_type', 'order_id');  // [order_id => order_type]
            }

            // 过滤出指定类型
            $arr['data'] = array_values(array_filter($arr['data'], function ($row) use ($orderType, $typeByOrderId) {
                $oid = isset($row['order_id']) ? (int)$row['order_id'] : 0;
                return $oid && isset($typeByOrderId[$oid]) && (int)$typeByOrderId[$oid] === $orderType;
            }));
        } else {
            $arr['data'] = [];
        }

        // 修正分页统计
        $arr['total'] = count($arr['data']);
        $per          = (int)($arr['per_page'] ?? 15);
        if ($per <= 0) { $per = 15; }
        $arr['last_page']    = max(1, (int)ceil($arr['total'] / $per));
        $arr['current_page'] = min(max(1, (int)($arr['current_page'] ?? 1)), $arr['last_page']);

        return $this->renderSuccess([
            'list'  => $arr, // 返回数组结构：total/per_page/current_page/last_page/data
            'words' => $this->setting['words']['values'],
        ]);
    }

}